import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions, URLSearchParams} from "@angular/http";
import {LocalStorageService} from './local-storage.service';

const ServerUrl = "http://www.ggcms.com/tbk/";
//const ServerUrl = "http://localhost:56327/";
const searchParams = {
  Platform: "1",
  PageSize: 12,
  PageNo: 1,
  Cat: "",
  query: ""
};
@Injectable()
export class ApisService {

  constructor(private http : Http) {}
  private lStorage : LocalStorageService=new LocalStorageService();
  //错误处理
  private handleError(error : any) : Promise < any > {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

  category() : Promise < any > {
    let keyName = "categoryList";
    let cateList = this
      .lStorage
      .getObject(keyName);
    if (cateList) {
      return new Promise(function (resolve, reject) {
        resolve(cateList);
      });
    }
    var url = "/assets/data/category.json";
    return this
      .http
      .get(url)
      .toPromise()
      .then(response =>{ 
        let json = response.json();
        this.lStorage.setObject(keyName,json);
        return json;
      })
      .catch(err => this.handleError(err));
  }

  coupon(data : any = {}) : Promise < any > {
    data.qtype = "coupon";
    var sdata = Object.assign({}, searchParams, data);
    var opt = new RequestOptions({search: sdata});

    var url = ServerUrl;
    return this
      .http
      .get(url, opt)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
  superCoupon(data : any = {}) : Promise < any > {
    data.qtype = "super";
    var sdata = Object.assign({}, searchParams, data);
    var opt = new RequestOptions({search: sdata});

    var url = ServerUrl;
    return this
      .http
      .get(url, opt)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
  qianggou(data : any = {}) : Promise < any > {
    data.qtype = "tqg";
    var sdata = Object.assign({}, searchParams, data);
    var opt = new RequestOptions({search: sdata});

    var url = ServerUrl;
    return this
      .http
      .get(url, opt)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }

  iteminfo(data:any){
    data.qtype = "info";
    var sdata = Object.assign({}, {Platform:1}, data);
    var opt = new RequestOptions({search: sdata});

    var url = ServerUrl;
    return this
      .http
      .get(url, opt)
      .toPromise()
      .then(response => response.json())
      .catch(err => this.handleError(err));
  }
}
